package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path"
	"synthesis-server/controller"
	"synthesis-server/middle"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			//接收客户端发送的origin （重要！）
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			//服务器支持的所有跨域请求的方法
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			//允许跨域设置可以返回其他子段，可以自定义字段
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
			// 允许浏览器（客户端）可以解析的头部 （重要）
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
			//设置缓存时间
			c.Header("Access-Control-Max-Age", "172800")
			//允许客户端传递校验信息比如 cookie (重要)
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		//允许类型校验
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "ok!")
		}

		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic info is: %v", err)
			}
		}()

		c.Next()
	}
}

func NewRouter() *gin.Engine {
	gin.SetMode(gin.ReleaseMode)

	server := gin.Default()
	server.Use(Cors())
	server.GET("/status", controller.Status)
	server.POST("/register", controller.Add)
	server.POST("/login", controller.IsExist)
	server.POST("/upload", func(c *gin.Context) {
		//从请求中读取文件
		println("may be upload")
		file, err := c.FormFile("f1") //从请求中获取携带参数
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"status": 0,
				"error":  err.Error(),
			})
		} else {
			dst := path.Join("/root/RTC/storage", file.Filename)
			err := c.SaveUploadedFile(file, dst)
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			println(dst)
			c.JSON(200, gin.H{
				"status": 1,
			})
		}
	})
	group := server.Group("/verify", middle.Getting)
	{
		//建立websocket连接的接口
		group.GET("/socket.io", RunWebSocket)
		//group.POST("/upload", func(c *gin.Context) {
		//	//从请求中读取文件
		//	println("may be upload")
		//	file, err := c.FormFile("f1") //从请求中获取携带参数
		//	if err != nil {
		//		c.JSON(http.StatusBadRequest, gin.H{
		//			"status": 0,
		//			"error":  err.Error(),
		//		})
		//	} else {
		//		dst := path.Join("./storage", file.Filename)
		//		c.SaveUploadedFile(file, dst)
		//		c.JSON(200, gin.H{
		//			"status": 1,
		//		})
		//	}
		//
		//})
	}

	return server
}
